<template>
  <view class="wrap">
    <view class="top">
      <view class="item">
        <view class="left">收货人</view>
        <u-input type="text" v-model="formData.itemName" placeholder="请填写收货人姓名" border="none" />
      </view>
      <view class="item">
        <view class="left">手机号码</view>
        <u-input type="number" v-model="formData.phone" placeholder="请填写收货人手机号" border="none" />
      </view>
      <view class="item">
        <view class="left">所在地区</view>
        <view class="flex-auto" @click="openTreePicker({}, 'refKuiTreePicker')">
          <u-text
            v-if="!formData.itemAddress"
            text="请选择所在地区"
            type="text"
            placeholder="省市区县、乡镇等"
            border="none"
            suffix-icon="arrow-right"
            word-wrap="normal"
            lines="1"
          />
          <u-text
            v-else
            :text="formData.itemAddress"
            type="text"
            placeholder="省市区县、乡镇等"
            border="none"
            suffix-icon="arrow-right"
            word-wrap="normal"
            lines="1"
          />
        </view>
      </view>
      <view class="item address">
        <view class="left">详细地址</view>
        <u-textarea
          v-model="formData.receiveHouseNumber"
          type="text"
          placeholder="街道、楼牌等"
          border="none"
          customStyle="background-color:#f2f2f2"
        />
      </view>
      <!-- <view class="site-clipboard">
				<textarea placeholder-class="line" value="" placeholder="粘贴文本,可自动识别姓名和地址等" />
				<view class="clipboard">
					地址粘贴板
					<u-icon name="arrow-down" class="icon" :size="20"></u-icon>
				</view>
			</view> -->
    </view>
    <view class="bottom">
      <view class="tag" v-if="tags && tags.length > 0">
        <view class="left">标签</view>
        <view class="right">
          <text
            class="tags"
            v-for="(item, index) in tags"
            :key="index"
            @tap="setTag(item)"
            :class="{ active: item.active }"
            >{{ item.name }}</text
          >
        </view>
      </view>
      <view class="default">
        <view class="left">
          <view class="set">设置默认地址</view>
          <view class="tips">提醒：每次下单会默认推荐该地址</view>
        </view>
        <view class="right">
          <u-switch active-color="#0175ff" @change="setDefault" v-model="isDefault" />
        </view>
      </view>
    </view>
    <u-picker mode="region" ref="uPicker" v-model="show" />
    <view class="addSite" @tap="toAddSite">
      <view class="add">保存 </view>
    </view>

    <kui-tree-picker
      ref="refKuiTreePicker"
      :title="treePicker.title"
      :enableLazy="treePicker.enableLazy"
      :props:="treePicker.props"
      :treeNone="treePicker.treeNone"
      :treeData="treePicker.treeData"
      :checkList="treePicker.checkList"
      :checkedValList="treePicker.checkedValList"
      @chargeValue="treePickerChargeValue"
      :lazyFun="lazyFun"
    />
  </view>
</template>

<script>
let self;
import { addAddr, addrDetailsById, regionLazytree } from "../api/addrManage";
export default {
  data() {
    return {
      isDefault: true,
      show: false,
      tags: [
        // { id: 1, name: '家', active: true },
        // { id: 2, name: '公司', active: false },
        // { id: 3, name: '学校', active: false },
      ],
      formData: {
        // customerInformationItemId: '',
        isDefault: "1",
        itemType: 11,
        itemAddress: "",
        itemName: "",
        phone: "",
        receiveHouseNumber: "",
        regionCode: "",
      },
      regionVOList: [], //服务区域信息集合
      regionCode: "", //服务区域编码,
      treePicker: {
        refName: null,
        keyName: null,
        isUse: false,
        title: "",
        treeData: [],
        checkList: [],
        checkedValList: [],
        currDepth: 0,
        props: {
          /*... */
        },
        option: {},
      },
    };
  },
  onLoad(opt) {
    self = this;
    if (opt.id) {
      this.formData.customerInformationItemId = opt.id;
      const { id } = opt;
      this.getAddrDetail(id);
      // 更新标题
      uni.setNavigationBarTitle({
        title: "编辑地址",
      });
    }
  },
  methods: {
    async getAddrDetail(id) {
      try {
        const { data } = await addrDetailsById(id);
        if (!data) throw new Error("获取地址详情失败");
        this.formData = data;
        this.isDefault = data.isDefault == 1;
        this.regionVOList = data.regionCode.split(",");
        this.regionCode = data.regionCode;
      } catch (error) {
        console.error(error);
        uni.showToast({
          title: error,
          icon: "none",
        });
      }
    },
    setDefault(e) {
      this.formData.isDefault = e ? 1 : 0;
    },
    showRegionPicker() {
      this.$refs.region.open();
    },
    //地区下拉选择
    finish: function (e) {
      // console.log("finish", e);
      this.formData.itemAddress = e.Address[1];
      this.formData.regionCode = e.ListID.join(",");
      this.regionVOList = e.ListID;
      this.itemAddress = e.Address[2];
    },
    setTag(item) {
      this.tags.map((v) => {
        if (v.name == item.name) {
          v.active = true;
        } else {
          v.active = false;
        }
      });
    },
    async toAddSite() {
      // 新增和保存是同一个接口
      // if (this.formData.customerInformationItemId) {
      //   return this.updateAddr();
      // }
      // 校验数据
      if (!this.formData.itemName) {
        return uni.showToast({
          title: "请填写收货人姓名",
          icon: "none",
        });
      }
      if (!this.formData.phone) {
        return uni.showToast({
          title: "请填写收货人手机号",
          icon: "none",
        });
      }
      if (!this.formData.itemAddress) {
        return uni.showToast({
          title: "请选择所在地区",
          icon: "none",
        });
      }
      if (!this.formData.receiveHouseNumber) {
        return uni.showToast({
          title: "请填写详细地址",
          icon: "none",
        });
      }
      try {
        const { id } = this.$store.getters.userInfo;
        const pam = {
          ...this.formData,
          customerInformationId: id,
          userId: id,
        };
        const { data, success } = await addAddr(pam);
        if (!success) throw new Error("保存地址失败");
        uni.navigateBack({
          success: () => {
            const timer = setTimeout(() => {
              clearTimeout(timer);
              uni.showToast({
                title: "保存地址成功",
                icon: "none",
              });
            }, 500);
          },
        });
      } catch (error) {
        console.error(error);
      }
    },

    // -- treePicker START ----------------------------------------------------------------------------
    async treePickerChargeValue(CCpeople, checkList, stackPath) {
      // 是否配置了指定用于显示和提交的字段
      const { comOption, hooks } = this.treePicker?.option;
      const { props, postKey } = comOption;

      const inkeyArray = [];
      let inkey = "";
      const inlableArray = [];
      let inlable = "";

      stackPath.map((v) => {
        // 默认获取选中项的“哪个值”做
        const lable = props.label || "name";
        inkeyArray.push(v[postKey]);
        inlableArray.push(v[lable]);
      });

      inkey = inkeyArray.join(",");
      inlable = inlableArray.join(",");

      console.log("treePickerChargeValue", {
        inkeyArray,
        inlableArray,
        inkey,
        inlable,
        checkList,
        stackPath,
      });
      // 强制刷新
      this.$forceUpdate();
      // const ref = this.$refs[this.treePicker.refName][0];
      // await ref.setValue(inkey, inlable, checkList);
      this.formData.itemAddress = inlable;
      this.formData.regionCode = inkey;
      this.regionVOList = inkeyArray;
      this.itemAddress = inlableArray;
    },
    async openTreePicker(optionNot, refName) {
      const option = {
        comOption: {
          // action: "/kingon-system/region/lazy-tree",
          param: {
            // parentId: 0,
            parentCode: "00",
          },
          // 数据深度
          depth: 0,
          enableLazy: true,
          postKey: "code",
          props: {
            label: "title",
            children: "children",
            multiple: false,
          },
        },
      };
      try {
        console.log("openTreePicker", option, refName);

        // ---- 将配置的值存入对应数据
        this.treePicker.refName = refName;
        this.treePicker.option = this.mergeComOption(this.treePicker, option.comOption);
        this.treePicker.isUse = true;

        await this.$nextTick();
        const { comOption } = this.treePicker.option;
        if (!comOption) throw new Error("TreePicker -> 缺少配置 comOption");
        const { /* action,  */ param, header, props } = comOption;

        // if (!action) throw new Error("TreePicker -> 请配置请求地址");
        const { data } = await regionLazytree(param || {}, header);

        const treeData = data.map((item) => {
          if (!item.children) item.children = [];
          // item.id = `${item[inkey]}`
          // item.name = item[inlable];
          item.canSelect = item.hasChildren == false ? false : true;
          return item;
        });
        this.treePicker.treeData = treeData;
        // this.$set(this.treePicker, 'treeData', treeData);

        await this.$nextTick();
        this.$refs.refKuiTreePicker.open({ props });
      } catch (error) {
        console.error(error);
        uni.showToast({
          title: "获取数据失败",
          icon: "error",
        });
      }
    },
    async lazyFun(item, parenNode, index) {
      const { comOption } = self.treePicker?.option;
      if (!comOption) return console.warn("TreePicker -> 缺少配置 comOption");
      // 自定义请求，并设置数据
      const { data } = await regionLazytree({ parentCode: parenNode.id });

      const treeData = data.map((item) => {
        if (!item.children) item.children = [];
        // 设置当前层级数据是否可选，（注意：设置成false，会往下触发）
        item.canSelect = true;
        // user 这个控制是否显示右边的右箭头按钮显示，<i v-if="!item.user"
        item.user = item.hasChildren === false ? true : false;
        return item;
      });
      parenNode.children = treeData;
      // const { lazyFun } = comOption;
      // if (lazyFun && typeof lazyFun === "function") lazyFun(item, parenNode, index);
      // else if (lazyFun && lazyFun instanceof Promise) await lazyFun(item, parenNode, index);
    },
    //  treePicker END ----
    // 合并comOpst 而不覆盖，因为有默认值的存在，同时也能减少配置编写
    mergeComOption(baseConfg, newComOption) {
      const baseComOption = baseConfg.option?.comOption || {};
      if (!newComOption) {
        baseConfg.option.comOption = baseComOption;
        return baseConfg.option;
      } else {
        baseConfg.option.comOption = { ...baseComOption, ...newComOption };
        return baseConfg.option;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.line {
  // color: $u-light-color;
  font-size: 28rpx;
}

.wrap {
  background-color: #f2f2f2;

  .top {
    background-color: #ffffff;
    // border-top: solid 2rpx $u-border-color;
    padding: 22rpx;

    .item {
      display: flex;
      font-size: 28rpx;
      line-height: 100rpx;
      align-items: center;
      // border-bottom: solid 2rpx $u-border-color;

      .left {
        width: 180rpx;
      }

      input {
        text-align: left;
      }
    }

    .address {
      padding: 20rpx 0;

      textarea {
        // width: 100%;
        height: 150rpx;
        background-color: #f7f7f7;
        line-height: 60rpx;
        margin: 40rpx auto;
        padding: 20rpx;
      }
    }

    .site-clipboard {
      padding-right: 40rpx;

      textarea {
        // width: 100%;
        height: 150rpx;
        background-color: #f7f7f7;
        line-height: 60rpx;
        margin: 40rpx auto;
        padding: 20rpx;
      }

      .clipboard {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        color: $u-tips-color;
        height: 80rpx;

        .icon {
          margin-top: 6rpx;
          margin-left: 10rpx;
        }
      }
    }
  }

  .bottom {
    margin-top: 20rpx;
    padding: 40rpx;
    padding-right: 0;
    background-color: #ffffff;
    font-size: 28rpx;

    .tag {
      display: flex;

      .left {
        width: 160rpx;
      }

      .right {
        display: flex;
        flex-wrap: wrap;

        .tags {
          width: 140rpx;
          padding: 10rpx 8rpx;
          border: solid 2rpx $u-border-color;
          text-align: center;
          border-radius: 50rpx;
          margin: 0 10rpx 20rpx;
          display: flex;
          font-size: 25rpx;
          align-items: center;
          justify-content: center;
          color: $u-content-color;
          line-height: 1;

          &.active {
            background-color: #0175ff /* $kui-color-theme; */;
            color: white;
          }
        }

        .plus {
          //padding: 10rpx 0;
        }
      }
    }

    .default {
      margin-top: 50rpx;
      display: flex;
      justify-content: space-between;
      border-bottom: solid 2rpx $u-border-color;
      line-height: 64rpx;

      .tips {
        font-size: 23rpx;
        color: $u-tips-color;
      }

      .right {
        padding-right: 6px;
      }
    }
  }
}

.addSite {
  display: flex;
  justify-content: space-around;
  width: 600rpx;
  line-height: 100rpx;
  position: absolute;
  bottom: 30rpx;
  left: 80rpx;
  background-color: #0175ff /* $kui-color-theme; */;
  border-radius: 60rpx;
  font-size: 30rpx;

  .add {
    display: flex;
    align-items: center;
    color: #ffffff;

    .icon {
      margin-right: 10rpx;
    }
  }
}
</style>
